package com.oromwin.repos.server.response.file;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposClientConfig;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.server.response.NormalResponse;

public class ReadFileResponse extends NormalResponse {
    private Log log = Logger.getLog(ReadFileResponse.class);
    private long FileBytes = 0L;
    private File LocalPath = null;

    public ReadFileResponse(File localPath) {
        LocalPath = localPath;
    }

    public void receive(DataInputStream dis) throws ReposException {
        try {
            Result = dis.readBoolean();
            Description = IOHelper.readUTF8(dis);
            FileBytes = dis.readLong();
            int off = 0;
            int len = ReposClientConfig.getDefaultBufferSize();
            int read = 0;
            byte[] b = new byte[len];
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(LocalPath));
            while (read < FileBytes) {
                int readBytes = dis.read(b, off, len);
                read += readBytes;
                bos.write(b, off, readBytes);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }
}
